package com.demo.util;

import com.demo.model.Project;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class FreeMarkerUtil {
    public static String process(String templateFileName, String company_name, Project project){
        // 1.配置FreeMarker
        Template template;
        Writer out = new StringWriter();

        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
            cfg.setDirectoryForTemplateLoading(new File("config/templates"));
            cfg.setDefaultEncoding("UTF-8");
            template = cfg.getTemplate(templateFileName);

            // 2.渲染FreeMarker模板
            Map<String, Object> model = new HashMap<>();
            model.put("company", company_name);
            model.put("item", project);

            template.process(model, out);
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
        return out.toString();
    }

}
